<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\user\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\Airport as AirportModel;
use app\user\model\Continent as ContinentModel;
use think\cache\driver\Redis;
use think\facade\Cache;
use think\validate\ValidateRule;

/**
 * 机场控制器
 * @package app\user\admin
 */
class Airport extends Admin
{
    /**
     * 机场列表
     * @author 李洪波 <361951119@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data_list = AirportModel::where($this->getMap())
            ->order($this->getOrder('id DESC'))
            ->paginate();
        if($data_list->items()){
            foreach ($data_list->items() as &$val){
                $country=ContinentModel::where(['id'=>$val['country'],'type'=>'country'])->value('name');
                $val['country']=$country;
                $city=ContinentModel::where(['id'=>$val['city'],'type'=>'city'])->value('name');
                $val['city']=$city;
                $val['terminal']=implode(',',json_decode($val['terminal'],true));
            }
        }
        $btn_access = [
            'title' => 'Import',
            'icon'  => 'fa fa-fw fa-upload',
            'class' => 'btn btn-primary ajax-post confirm',
            'href'  => url('import')
        ];

        $down_access = [
            'title' => 'Download',
            'icon'  => 'fa fa-fw fa-download',
            'class' => 'btn btn-primary',
            'href'  => PUBLIC_PATH. 'static/admin/download/airport.xls',
            'target'=>'_blank'
        ];

        $countries=ContinentModel::where(['type'=>'country'])->column(['id','name']);
        $cities=ContinentModel::where(['type'=>'city'])->column(['id','name']);
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->setTableName('airport')
            ->addTopButton('add',['title'=>'Add'])
            ->addTopButton('custom', $btn_access, ['area' => ['800px', '60%'], 'title' => ['Import', 'font-size:18px;']])
            ->addTopButton('custom',$down_access)
            ->addRightButton('edit',['title'=>'edit'])
            ->addRightButton('delete',['title'=>'delete','data-title' => 'Warning! After deleting the data, users will not be able to see the content of that airport, and the merchants associated with that airport will need to reset the airport data, sure you want to continue?','data-confirm'=>'confirm','data-cancel'=>'cancel'])
            ->addColumns([
                ['id', 'ID'],
                ['name', 'Airport'],
                ['iata', 'IATA'],
                ['terminal', 'Terminal'],
                ['merchant', 'Merchant'],
                ['city', 'City'],
                ['country', 'Country'],
                ['update_user', 'Updater'],
                ['update_time', 'Last update time'],
                ['right_button', 'Operation', 'btn'],
            ])
            ->setColumnWidth([
                'id'=>50,
                'name'=>80,
                'iata'=>60,
                'city'=>80,
                'country'=>80,
                'update_time'=>120,
                'right_button'=>60
            ])
            ->setRowList($data_list)

            ->setSearchArea([
                ['text', 'name', 'Airport','like'],
                ['select', 'country', 'Country', '', '', $countries],
                ['select', 'city', 'City', '', '', $cities]
            ])
            ->fetch();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $data['name'] == '' && $this->error('Please fill in the airport name');
            $data['iata'] == '' && $this->error('Please fill in the iata');
            $data['continent'] == '' && $this->error('Please fill in the continent');
            $data['country'] == '' && $this->error('Please fill in the country');
            $data['city'] == '' && $this->error('Please fill in the city');
            $data['terminal'] == '' && $this->error('Please fill in the terminal');
            ($data['longitude'] == '' || !is_numeric($data['longitude'])) && $this->error('Please fill in the Longitude or Incorrect format');
            ($data['latitude'] == '' || !is_numeric($data['longitude'])) && $this->error('Please fill in the Latitude or Incorrect format');
            if(!$this->check($data['name'])) $this->error('Data duplicated, please re-enter');
            $list = [];
            $list['name']=$data['name'];
            $list['iata']=$data['iata'];
            $list['terminal']=json_encode(explode(',',$data['terminal']));
            $list['city']=$data['city'];
            $list['country']=$data['country'];
            $list['continent']=$data['continent'];
            $list['longitude']=trim($data['longitude']);
            $list['latitude']=trim($data['latitude']);
            $list['update_time']=date('Y-m-d H:i:s');
            $list['create_time']=date('Y-m-d H:i:s');
            $list['update_user']=session('user_auth')['username'];
            $continentModel = new AirportModel();
            $insertID=$continentModel->insertGetId($list);
            if ($insertID) {
                //添加机场经纬度信息到redis
                if($list['latitude'] && $list['longitude']){
                    $handler=Cache::store('redis')->handler();
                    $handler->geoadd(config('redis.redis_key.airport_location'),$list['longitude'],$list['latitude'],'airport_'.$insertID);
                }
                $this->success('add success', 'index');
            } else {
                $this->error('add failed');
            }
        }
        $continents=ContinentModel::where(['type'=>'continent'])->column(['id','name']);
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', 'Airport'],
                ['text', 'iata', 'IATA'],
            ])
            ->addLinkage('continent', 'Select a continent', '', $continents, '', url('get_city'), 'country,city')
            ->addLinkage('country', 'Select a country', '', '', '', url('get_area'), 'city')
            ->addSelect('city', 'Select a city')
            ->addFormItems([
                ['text', 'terminal', 'Terminal','Multiple terminals separated by commas'],
                ['text', 'longitude', 'Longitude'],
                ['text', 'latitude', 'Latitude'],
            ])
            ->layout(['longitude'=>6,'latitude'=>6,'continent'=>4,'country'=>4,'city'=>4])
            ->fetch();
    }


    public function edit($id = 0)
    {
        if ($id === 0) $this->error('missing parameter');

        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $data['name'] == '' && $this->error('Please fill in the airport name');
            $data['iata'] == '' && $this->error('Please fill in the iata');
            $data['continent'] == '' && $this->error('Please fill in the continent');
            $data['country'] == '' && $this->error('Please fill in the country');
            $data['city'] == '' && $this->error('Please fill in the city');
            $data['terminal'] == '' && $this->error('Please fill in the terminal');
            ($data['longitude'] == '' || !is_numeric($data['longitude'])) && $this->error('Please fill in the Longitude or Incorrect format');
            ($data['latitude'] == '' || !is_numeric($data['longitude'])) && $this->error('Please fill in the Latitude or Incorrect format');
            $data['terminal']=json_encode(explode(',',$data['terminal']));
            if(!$this->check($data['name'],$id)) $this->error('Data duplicated, please re-enter');
            $data['update_time']=date('Y-m-d H:i:s');
            $data['update_user']=session('user_auth')['username'];
            if (AirportModel::update($data,['id'=>$id])) {
                //添加机场经纬度信息到redis
                if($data['latitude'] && $data['longitude']){
                    $handler=Cache::store('redis')->handler();
                    $handler->geoadd(config('redis.redis_key.airport_location'),trim($data['longitude']),trim($data['latitude']),'airport_'.$id);
                }
                $this->success('edit success', 'index');
            } else {
                $this->error('edit failed');
            }
        }
        // 获取数据
        $info = AirportModel::get($id);
        $info['terminal']=implode(',',json_decode($info['terminal'],true));
        $continents=ContinentModel::where('type','continent')->column(['id','name']);
        $country = ContinentModel::where('parent_id', $info['continent'])->column('id,name');
        $city = ContinentModel::where('parent_id', $info['country'])->column('id,name');
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->addFormItems([
                ['text', 'name', 'Airport'],
                ['text', 'iata', 'IATA'],
            ])
            ->addLinkage('continent', 'Select a continent', '', $continents, '', url('get_city'), 'country,city')
            ->addLinkage('country', 'Select a country', '', $country , '', url('get_area'), 'city')
            ->addSelect('city', 'Select a city', '', $city)
            ->addFormItems([
                ['text', 'terminal', 'Terminal','Multiple terminals separated by commas'],
                ['text', 'longitude', 'Longitude'],
                ['text', 'latitude', 'Latitude'],
            ])
            ->layout(['longitude'=>6,'latitude'=>6,'continent'=>4,'country'=>4,'city'=>4])
            ->setFormData($info)
            ->fetch();
    }

    private function check($name,$id=0){
        $id=AirportModel::where(['name'=>$name])
            ->when($id,function ($query)use($id){
                $query->where('id','neq',$id);
            })
            ->value('id');
        if($id){
            return false;
        }else{
            return true;
        }
    }



    public function import(){
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $file_path=get_file_path($data['file']);
            if(empty($data['file'])) $this->error('please upload excel file!');
//            $ext = pathinfo($file_path);
//            //设置excel格式
//            $type = strtolower($ext["extension"]);
//            if($type=='xlsx'){
//                $type='Excel2007';
//            }elseif ($type=='csv'){
//                $type='csv';
//            }else{
//                $type='Excel5';
//            }
            require_once($_SERVER['DOCUMENT_ROOT'].'/../extend/PHPExcel/PHPExcel/IOFactory.php');
            $objPHPExcel = \PHPExcel_IOFactory::load($_SERVER['DOCUMENT_ROOT'].$file_path);
            //默认选中sheet0表
            $sheetSelected = 0;
            $objPHPExcel->setActiveSheetIndex($sheetSelected);
            //获取表格行数
            $rowCount = $objPHPExcel->getActiveSheet()->getHighestRow();
            //获取表格列数
            $columnCount = $objPHPExcel->getActiveSheet()->getHighestColumn();
            $list=[];
            for ($row = 2; $row <= $rowCount; $row++) {
                $dataArr = array();
                for ($column = 'A'; $column <= $columnCount; $column++) {
                    $dataArr['name']=trim($objPHPExcel->getActiveSheet()->getCell('A' . $row)->getValue());
                    $dataArr['iata']=trim($objPHPExcel->getActiveSheet()->getCell('B' . $row)->getValue());
                    $dataArr['terminal']=trim($objPHPExcel->getActiveSheet()->getCell('C' . $row)->getValue());
                    $dataArr['country']=trim($objPHPExcel->getActiveSheet()->getCell('D' . $row)->getValue());
                    $dataArr['city']=trim($objPHPExcel->getActiveSheet()->getCell('E' . $row)->getValue());
                    $dataArr['longitude']=trim($objPHPExcel->getActiveSheet()->getCell('F' . $row)->getValue());
                    $dataArr['latitude']=trim($objPHPExcel->getActiveSheet()->getCell('G' . $row)->getValue());
                }
                if(!is_numeric($dataArr['latitude']) || !is_numeric($dataArr['longitude'])){
                    $this->error('excel latitude or longitude must be number');
                }
                $list[]=$dataArr;
            }
            if($list){
                $airportModel=new AirportModel();
                $rep=$airportModel->addAll($list,session('user_auth')['username']);
                if($rep['code']==1){
                    $this->success('excel file import success','index', '_parent_reload');
                }else{
                    $this->error($rep['msg']);
                }
            }else{
                $this->error('excel file data is empty!');
            }

        }

        return ZBuilder::make('form')
            ->addFile('file', 'Airport File', '', '', '','xlsx,csv,xls')
            ->fetch();
    }

    // 根据省份获取城市
    public function get_city($continent = '')
    {
        $countries=ContinentModel::where(['type'=>'country','parent_id'=>$continent])->column(['id','name']);
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $lists=[];
        if($countries){
            foreach ($countries as $key=>$val){
                $list['key']=$key;
                $list['value']=$val;
                $lists[]=$list;
            }
        }
        $arr['list'] = $lists;
        return json($arr);
    }

    // 根据城市获取地区
    public function get_area($country = '')
    {
        $cities=ContinentModel::where(['type'=>'city','parent_id'=>$country])->column(['id','name']);
        $arr['code'] = '1'; //判断状态
        $arr['msg'] = '请求成功'; //回传信息
        $lists=[];
        if($cities){
            foreach ($cities as $key=>$val){
                $list['key']=$key;
                $list['value']=$val;
                $lists[]=$list;
            }
        }
        $arr['list'] = $lists;
        return json($arr);
    }

    public function delete($record = [])
    {
        $ids   = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        AirportModel::where(['id'=>$ids])->delete();
        $handler=Cache::store('redis')->handler();
        $handler->ZREM(config('redis.redis_key.airport_location'),'airport_'.$ids);
        $this->success('delete success','index');
    }
}
